//
//  PgyUtil.swift
//  SYGovernment
//
//  Created by 思域 on 2020/10/16.
//  Copyright © 2020 思域. All rights reserved.
//

import Alamofire
import Foundation

/// 蒲公英工具
public struct PgyUtil {
    private static var apiKey: String?
    private static var appKey: String?

    /// 设置apiKey和appKey
    /// - Parameters:
    ///   - apiKey: apiKey
    ///   - appKey: appKey
    public static func setup(_ apiKey: String, appKey: String) {
        self.apiKey = apiKey
        self.appKey = appKey
    }

    /// 检查更新
    public static func checkUpdate() {
        guard let api = apiKey, let app = appKey else {
            fatalError("call PgyUtil.setup() first")
        }
        let info = Bundle.main.infoDictionary!
        let version = "\(info["CFBundleVersion"] as! String)"
        let params = ["_api_key": api,
                      "appKey": app,
                      "buildVersion": version,
        ]

        let b = "aHR0cHM6Ly93d3cucGd5ZXIuY29tL2FwaXYyL2FwcC9jaGVjaw=="
        guard let data = Data(base64Encoded: b), let url = String(data: data, encoding: .utf8) else {
            return
        }
        AF.request(url, method: .post, parameters: params).responseJSON { res in
            if res.error == nil {
                guard let dict = res.value as? [String: Any] else {
                    return
                }
                SLLog(dict)
                guard let c = dict["code"] as? Int, c == 0 else {
                    return
                }
                let data = dict["data"] as? [String: Any]
                if let buildBuildVersion = data?["buildVersionNo"] as? String,
                   let serviceV = Int(buildBuildVersion),
                   let currentV = Int(version),
                   serviceV > currentV {
                    let urlStr = (data?["downloadURL"] as? String) ?? ""
                    if let url = URL(string: urlStr) {
                        install(url, lates: serviceV, current: currentV, buildUpdateDescription: "")
                    }
                }
            }
        }
    }

    private static func install(_ url: URL, lates: Int, current: Int, buildUpdateDescription: String?) {
        if UIApplication.shared.canOpenURL(url) == false {
            return
        }
        let vc = UIAlertController(title: "发现新版本", message: "当前build\(current)，最新build\(lates)，是否安装？", preferredStyle: .alert)
        vc.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        vc.addAction(UIAlertAction(title: "安装", style: .default, handler: { _ in
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }))
        UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true, completion: nil)
    }
}
